package com.ks.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 
 * @author pks
 * @version 2019年10月14日 
 */
public class SCheckUrlPath {

	public static int checkHttpUrl(String url) throws Exception {
		URL u = null;
		HttpURLConnection oc = null ;
		int status = 404;
		try {
			u = new URL(url);
			oc = (HttpURLConnection) u.openConnection();
			oc.setUseCaches(false);
			oc.setConnectTimeout(2000);
			oc.setReadTimeout(2000);
			oc.connect();
			status = oc.getResponseCode();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(oc!=null) oc.disconnect();
		}
		return status;
	}
	
	public static int checkHttpsUrl(String url) throws Exception {
		URL u = null;
		HttpsURLConnection https_oc = null ;
		int status = 404;
		try {
			u = new URL(url);
			TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					@Override
					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}
					@Override
					public void checkServerTrusted(X509Certificate[] arg0, String arg1)
							throws CertificateException {
					}
					@Override
					public void checkClientTrusted(X509Certificate[] arg0, String arg1)
							throws CertificateException {
					}
				}	
			};
	        SSLContext sc = SSLContext.getInstance("SSL");
	        sc.init(null, trustAllCerts, new java.security.SecureRandom());
	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	        HostnameVerifier allHostsValid = new HostnameVerifier(){
	        	@Override
				public boolean verify(String arg0, SSLSession arg1) {
					 return true;
				}
	        };
	        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	        https_oc = (HttpsURLConnection) u.openConnection();
	        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
	        https_oc.setSSLSocketFactory(sslSocketFactory);
	        https_oc.setUseCaches(false);
	        https_oc.setConnectTimeout(2000);
	        https_oc.setReadTimeout(2000);
	        status = https_oc.getResponseCode();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(https_oc!=null) https_oc.disconnect();
		}
		return status;
	}
	
}
